package org.edith.shiro.filter;

import org.edith.shiro.constant.HttpConstant;
import org.edith.shiro.context.WebContext;
import org.edith.shiro.util.RequestUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 2020-04-16 12:56
 *
 * @author LCY
 */
@WebFilter(urlPatterns="/*",filterName = "webContextFilter")
public class WebContextFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        String token = request.getHeader( HttpConstant.AUTHORIZATION);
        String ipAddress = RequestUtils.getIPAddress(request);
        Map<String,String> webContext = new HashMap<>();
        webContext.put( "token", token);
        webContext.put( "ipAddress", ipAddress);
        WebContext.getThreadLocal().set( webContext );
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
